import 'package:fish_redux/fish_redux.dart';
import 'package:flutter/cupertino.dart' hide Action;
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:intl/intl.dart';
import 'package:www.znpigai.teacher/home_page/subject_tab_component/item/state.dart';
import 'package:www.znpigai.teacher/utils/http.dart';
import 'package:www.znpigai.teacher/utils/nav.dart';
import 'package:www.znpigai.teacher/utils/progress_dialog.dart';
import 'package:www.znpigai.teacher/utils/util.dart';

import 'action.dart';
import 'state.dart';

Effect<HomeworkPostState> buildEffect() {
  return combineEffects(<Object, Effect<HomeworkPostState>>{
    HomeworkPostAction.onDone: _onDone,
    HomeworkPostAction.onSubject: _onSubject,
    HomeworkPostAction.onEdit: _onEdit,
    HomeworkPostAction.onStartTime: _onStartTime,
    HomeworkPostAction.onEndTime: _onEndTime,
  });
}

void _onSubject(Action action, Context<HomeworkPostState> ctx) async {
  var subject = await Navigator.of(ctx.context).pushNamed(Nav.SUBJECT_LIST);
  print(subject);
  if (subject is SubjectState) {
    ctx.dispatch(HomeworkPostActionCreator.edit({
      'title': subject.title,
      'demand': subject.demand,
      'keywords': subject.keywordList.join(' ') ?? '',
      'ideation': subject.ideation ?? ''
    }));
  }
}

void _onEdit(Action action, Context<HomeworkPostState> ctx) async {
  var inputType = action.payload;
  var title = '';
  var value = '';
  switch (inputType) {
    case 'title':
      title = '请输入标题';
      value = ctx.state.title;
      break;
    case 'demand':
      title = '请输入作文要求';
      value = ctx.state.demand;
      break;
    case 'ideation':
      title = '请输入构思点评';
      value = ctx.state.ideation;
      break;
    case 'keywords':
    default:
      title = '请输入中心词';
      value = ctx.state.keywords;
      break;
  }

  String ret = await Util.showInputDialog(title, '', value, title, ctx.context);
  if (ret != null) {
    ctx.dispatch(HomeworkPostActionCreator.edit({inputType: ret}));
  }
}

void _onStartTime(Action action, Context<HomeworkPostState> ctx) async {
  DatePicker.showDateTimePicker(ctx.context, showTitleActions: true,
      onChanged: (date) {
    print('change $date');
  }, onConfirm: (start) {
    ctx.dispatch(HomeworkPostActionCreator.startTime(start));
    if (start.isAfter(ctx.state.end)) {
      ctx.dispatch(HomeworkPostActionCreator.endTime(start));
    }
  }, currentTime: DateTime.now(), locale: LocaleType.zh);
}

void _onEndTime(Action action, Context<HomeworkPostState> ctx) async {
  DatePicker.showDateTimePicker(ctx.context, showTitleActions: true,
      onChanged: (date) {
    print('change $date');
  }, onConfirm: (end) {
    if (end.isAfter(ctx.state.start)) {
      ctx.dispatch(HomeworkPostActionCreator.endTime(end));
    } else {
      Util.alert('截止时间必须晚于开始时间', ctx.context);
    }
  }, currentTime: DateTime.now(), locale: LocaleType.zh);
}

Future _onDone(Action action, Context<HomeworkPostState> ctx) async {
  if (ctx.state.maxCount * 50 <= ctx.state.minCount * 50) {
    Util.alert('最多字数必须大于最少字数', ctx.context);
    return;
  }

  if (ctx.state.maxScore <= ctx.state.minScore) {
    Util.alert('最高分数必须大于最低分数', ctx.context);
    return;
  }

  var pr = new ProgressDialog(ctx.context)..setMessage('请等待...');
  pr.show();
  var url = '/correct/teacher/api/homework/add.mvc';
  HttpResult result = await Http.post(url, data: {
    "codes": ctx.state.selectClasses.join(', '),
    "title": ctx.state.title,
    "articleType": ctx.state.type,
    "demand": ctx.state.demand ?? '',
    "startTime": DateFormat('yyyy/MM/dd kk:mm:ss').format(ctx.state.start),
    "endTime": DateFormat('yyyy/MM/dd kk:mm:ss').format(ctx.state.end),
    "minCharacterCount": ctx.state.minCount.toInt() * 50,
    "maxCharacterCount": ctx.state.maxCount.toInt() * 50,
    "lowScore": ctx.state.minScore.toInt(),
    "highScore": ctx.state.maxScore.toInt(),
    "allowWritingAssistant": true,
    "allowPaste": true,
    "ideation": ctx.state.ideation ?? '',
    // "fullScore": ctx.state.maxScore,
    "digressCheck": false,
    "similarityCheck": false,
    "writingReferenceId": '',
    "selfWritingReferenceId": '',
    "keywords": ctx.state.keywords,
    "lowestScore": ctx.state.passScore.toInt() * 5,
  });
  pr.hide();

  if (result.success) {
    await Util.showMsgDialog('作业发布成功', '', ctx.context);
    Navigator.of(ctx.context)
        .pushNamedAndRemoveUntil(Nav.HOME, (Route<dynamic> route) => false);
  } else {
    Util.alert(result.errorMsg, ctx.context);
  }
}
